<template>
    <el-dialog v-model="visible" title="表格列配置" width="600px">
      <el-table :data="columns" border style="width: 100%">
        <el-table-column prop="label" label="列名" width="180" />
        <el-table-column prop="prop" label="字段" width="180" />
        <el-table-column label="显示">
          <template #default="{ row }">
            <el-switch v-model="row.visible" @change="handleChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ $index }">
            <el-button link type="primary" @click="moveUp($index)" :disabled="$index === 0">上移</el-button>
            <el-button link type="primary" @click="moveDown($index)" :disabled="$index === columns.length - 1">下移</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script lang="ts" setup>
  import { ref, watch } from 'vue'
  
  const props = defineProps({
    modelValue: {
      type: Array,
      required: true
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'change'])
  
  const visible = ref(false)
  const columns = ref([])
  
  // 打开弹窗
  const open = () => {
    columns.value = JSON.parse(JSON.stringify(props.modelValue))
    visible.value = true
  }
  
  // 列顺序调整
  const moveUp = (index) => {
    if (index > 0) {
      const temp = columns.value[index]
      columns.value.splice(index, 1)
      columns.value.splice(index - 1, 0, temp)
    }
  }
  
  const moveDown = (index) => {
    if (index < columns.value.length - 1) {
      const temp = columns.value[index]
      columns.value.splice(index, 1)
      columns.value.splice(index + 1, 0, temp)
    }
  }
  
  // 确认配置
  const handleConfirm = () => {
    emit('update:modelValue', columns.value)
    emit('change', columns.value)
    visible.value = false
  }
  
  // 单个列显示状态变化
  const handleChange = (row) => {
    emit('change', columns.value)
  }
  
  defineExpose({
    open
  })
  </script>
  
  <style scoped>
  .el-table {
    margin-bottom: 20px;
  }
  </style>